package com.jw.blog.listener;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jw.blog.utils.AddressUtil;
import com.jw.blog.utils.UserIpUtil;
import com.jw.blog.wblog.entity.Visit;
import com.jw.blog.wblog.mapper.VisitMapper;
import com.jw.blog.wblog.service.IVisitService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * @author wan Email-wlf18726994755@163.com
 * @version 1.0
 * @className VisitTimesListener
 * @date 2020/7/1 8:57
 **/
@WebListener
public class VisitTimesListener implements ServletRequestListener {
    @Resource
    private VisitMapper visitMapper;

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        HttpSession session = request.getSession();
        Visit visit = null;
        try {
            if (session.isNew()) {
                // 先判断当前ip24小时内是否已经访问过,如果没有则保存当前访问记录
                visit = new Visit();
                visit.setIp(UserIpUtil.getIp(request));
                //24小时内访问过就不会被记录。
                LocalDateTime dateTime = LocalDateTime.now().minusHours(24);
                visit.setTime(LocalDateTime.now());
                String userAgent = request.getHeader("user-agent");
                visit.setUserAgent(userAgent);
                QueryWrapper<Visit> wrapper = new QueryWrapper<>();
                wrapper.lambda().like(Visit::getIp,visit.getIp());
                wrapper.lambda().ge(Visit::getTime,dateTime);
                wrapper.lambda().like(Visit::getUserAgent,visit.getUserAgent());
                UserAgent ua = UserAgentUtil.parse(userAgent);
                synchronized (this) {
                    if (visitMapper.selectList(wrapper).size() == 0) {
                        visit.setPlatformType(ua.getOs().toString());
                        visit.setBrowserType(ua.getBrowser().toString()+ "  "+ ua.getVersion());
                        visit.setUrl(request.getRequestURL().toString());
                        visit.setCity(new AddressUtil().getAddresses("ip=" + visit.getIp(), "GBK"));


                        visitMapper.insert(visit);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
